var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var date_util = require('../../utils/date_util.js');
var user = require('../../services/user.js');
var base64 = require('../../utils/base64.js')
var version = require('../../config/version.js');
var WxSearch = require('../../wxSearch/wxSearch.js')
const logger = wx.getLogManager({
  level: 1
})
var app = getApp();
const navigationBarHeight = (getApp().statusBarHeight + 44) + 'px'

Page({
  data: {
    navigationBarTitle: '搜索现场',
    navigationBarHeight,
    statusBarHeight: app.statusBarHeight + 'px',
    systemInfo: {},
    winHeight: 0,
    page: 1,
    size: 10000,
    userInfo: app.globalData.userInfo,
    auth: app.globalData.auth,
    hasPhone: app.globalData.hasPhone,

    actList: [],
    isSearch: false,
    keyword: '',
    showPage: false,
    labels: [],
    labelNames: []

  },
  onLoad: function(options) {
    wx.hideTabBar();
    // app.editTabbar();
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          winHeight: res.windowHeight,
          systemInfo: res
        });
      }
    });
    wx.showShareMenu();

    WxSearch.init(that, 43, [{
      tagName: '#古典音乐',
      tagId: 'ee2951bc9c3b4e45aa10739cbfd1fda'
    }, {
      tagName: '#英式摇滚',
      tagId: '0a1fb31ce1e446169c0d65bec34e2be1'
    }, {
      tagName: '#世界音乐',
      tagId: '0fe2838cc9d3436e8838475db6be2295'
    }, {
      tagName: '#核',
      tagId: '2192cadd5a224d80b075d3833e5fba3b'
    }, {
      tagName: '#电子',
      tagId: '2c52c239f60a4453a656370f8368c8da'
    }, {
      tagName: '#摇滚',
      tagId: '30570af4163f410eb4468baf9c763a28'
    }, {
      tagName: '#后摇',
      tagId: '320e751aec494ed1a534617e32149c2d'
    }, {
      tagName: '#朋克',
      tagId: '40f458abe35c4d338d0b9b21bf7f2fe7'
    }, {
      tagName: '#爵士',
      tagId: '43cdd57508564159843342d3247d0838'
    }, {
      tagName: '#说唱',
      tagId: '4be34f2d46ff4e9caa75b07a5b466265'
    }, {
      tagName: '#R&B',
      tagId: '5786676b0dd54631b11cea8c3088f9a2'
    }, {
      tagName: '#民谣',
      tagId: '7d0042b673e8496aa07961cdd4410b53'
    }, {
      tagName: '#金属',
      tagId: 'b717b4b4c5ee4384b7f5027ba0f55000'
    }, {
      tagName: '#布鲁斯',
      tagId: 'be9ea4f7467e4f0d8b43b7157ffd5338'
    }, {
      tagName: '#二次元',
      tagId: 'd540a9c2af31486f907f1960b4d79800'
    }, {
      tagName: '#流行',
      tagId: 'd8bf88e48469411e905731ad170f6e63'
    }, {
      tagName: '#独立',
      tagId: 'ee2951cb9c3b4e45aa10b793cbfd1fda'
    }, {
      tagName: '#雷鬼',
      tagId: 'fe780966b5da4621a6e2ce643c957d70'
    }]);
    WxSearch.initMindKeys([]);

  },
  //检索组件

  wxSearchFn: function(e) {
    var that = this
    WxSearch.wxSearchAddHisKey(that);

    var keyword = that.data.wxSearchData.value

    if (that.data.labels.length <= 0 && (!keyword || keyword == '')) {
      wx.showModal({
        title: '输入为空',
        showCancel: false,
        content: '亲爱的主人,忘了选择风格或者输入检索词啦!'
      })
    } else {
      that.showLoadTip()
      that.setData({
        isSearch: true,
        showPage: false,
      })
      var lab = that.data.labels.join(",");
      var timestap = new Date().getTime() + 365 * 24 * 60 * 60 * 1000
      util.pututrequest(api.searchAct + '?keywords=' + keyword + '&page=' + that.data.page + '&tagIds=' + lab + '&hasBegin=1', 'GET').then((res) => {
        if (res && res.code == 200) {
          that.dealnewData(res.data)
          wx.hideLoading()
        }
      })
    }

  },
  wxSearchInput: function(e) {
    var that = this
    WxSearch.wxSearchInput(e, that);
  },
  wxSerchFocus: function(e) {
    var that = this
    WxSearch.wxSearchFocus(e, that);
  },
  wxSearchBlur: function(e) {
    var that = this
    WxSearch.wxSearchBlur(e, that);
  },
  wxSearchLabelTap: function(e) {
    var that = this
    WxSearch.wxSearchLabelTap(e, that);
    var keyword = e.target.dataset.key
    var lab = that.data.labels
    var labelNames = that.data.labelNames
    var index = lab.indexOf(keyword.tagId)
    if (index != -1) {
      lab.splice(index, 1)
      labelNames.splice(index, 1)
    } else {
      lab.unshift(keyword.tagId)
      labelNames.unshift(keyword.tagName)
    }

    that.setData({
      labels: lab,
      labelNames: labelNames
    })

  },
  wxSearchKeyTap: function(e) {
    var that = this
    WxSearch.wxSearchKeyTap(e, that);
    var keyword = e.target.dataset.key
    if (keyword && keyword != '') {
      that.showLoadTip()
      that.setData({
        isSearch: true,
        showPage: false,
      })
      var lab = that.data.labels.join(",")
      var timestap = new Date().getTime() + 365 * 24 * 60 * 60 * 1000
      util.pututrequest(api.searchAct + '?keywords=' + keyword + '&page=' + that.data.page + '&tagIds=' + lab + '&hasBegin=1', 'GET').then((res) => {
        if (res && res.code == 200) {
          that.dealnewData(res.data)
          wx.hideLoading()
        }
      })
    } else {
      wx.showModal({
        title: '输入为空',
        showCancel: false,
        content: '亲爱的主人,忘了输入检索词啦!'
      })
    }
  },
  wxSearchDeleteKey: function(e) {
    var that = this
    WxSearch.wxSearchDeleteKey(e, that);
  },
  wxSearchDeleteAll: function(e) {
    var that = this;
    WxSearch.wxSearchDeleteAll(that);
  },
  wxSearchTap: function(e) {
    var that = this
    WxSearch.wxSearchHiddenPancel(that);
  },

  //检索组件

  showLoadTip: function() {
    wx.showLoading({
      title: '正在加载中...',
      mask: true
    })
  },
  onMyevent: function(e) {
    this.setData({
      userInfo: e.detail.paramBtoA.userInfo,
      auth: e.detail.paramBtoA.auth,
      hasPhone: e.detail.paramBtoA.hasPhone
    })
  },

  onReady: function() {},
  onShow: function() {

  },
  onHide: function() {},
  onUnload: function() {},

  backhome: function() {
    var that = this;
    wx.navigateBack({
      delta: 1
    })
  },
  dealnewData: function(newDataArr) {
    var that = this
    if (newDataArr && newDataArr.length > 0) {
      var list = that.data.actList;
      for (var i = 0; i < newDataArr.length; i++) {
        var act = newDataArr[i].activity
        var venue = newDataArr[i].venue

        var begin = date_util.convertTime(act.beginTime);
        var end = date_util.convertTime(act.endTime);
        var title_str = util.getTextLength(act.name) > 50 ? act.name.substr(0, 30) + '...' : act.name;
        // var area_str = venue?util.mixTextOverflow(venue.name, 8):'';
        var area_str = venue ? venue.name : '';
        var week_str = date_util.getWeek(act.beginTime);
        act.begin = begin
        act.end = end
        act.week = week_str
        act.title_str = title_str
        act.area_str = area_str
        act.acti_photo = act.coverUrl + "?imageMogr2/thumbnail/" +
          370 +
          "x" +
          "/format/jpg/size-limit/80k!"

        list.push(act);
      }
      that.setData({
        actList: list,
        showPage: true,
      })
    } else {
      that.setData({
        actList: [],
        showPage: true,
      })
    }
  },

  keywordInput: function(e) {
    this.setData({
      keyword: e.detail.value
    })
    if (!this.data.keyword || this.data.keyword == '') {
      this.setData({
        actList: [],
        isSearch: false,
      })
    }
  },

  gotoUpload: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index
    var item = that.data.actList[index]

    let itemStr = JSON.stringify(item)
    let item64 = base64.encode(itemStr)
    let itemEncode = encodeURIComponent(item64)
    var timestamp = new Date().getTime()
    if (item.begin_time > timestamp) {
      wx.showModal({
        title: '活动尚未开始',
        showCancel: false,
        content: '亲爱的主人,先按耐住激动的心,这个活动还没开始呢!'
      })
      return
    }


    // 业务
    if (that.data.auth && that.data.hasPhone) {
      wx.navigateTo({
        url: '/pages/upload/upload?dataObj=' + itemEncode,
        success: function() {},
        fail: function() {},
        complete: function() {}
      })
      // 业务
    } else {
      // 权限控制
      that.auth = that.selectComponent("#auth");
      util.getScope('scope.userInfo').then(function(resss) {
        if (resss) {
          that.auth.hideAuth();
          ///防止緩存失效带来的问题
          let code = null;
          return that.login().then((res) => { //userInfo
            code = res.code;
            wx.getUserInfo({
              withCredentials: true,
              success: function(res_user) {
                //先去登陆        
                wx.request({
                  url: api.userAuth,
                  data: {
                    platform: 'wx',
                    authorizationCode: code,
                    userEncryptrfData: res_user.encryptedData,
                    iv: res_user.iv
                  },
                  method: 'POST',
                  header: {
                    'Content-Type': 'application/json',
                    'accessToken': wx.getStorageSync('token'),
                    'appVersion': version.appVersion,
                    'deviceModel': getApp().globalData.systemInfo.model,
                    'platform': 'wx',
                    'build': version.build,
                    'deviceMachineCode': '',
                    'deviceOS': getApp().globalData.systemInfo.system.split(" ")[0],
                    'deviceOSVersion': getApp().globalData.systemInfo.system,
                  },
                  success: function(res) {
                    if (res && res.statusCode == 200 && res.data.code == 200) {
                      wx.setStorageSync('token', res.data.data.token);
                      app.globalData.token = res.data.data.token;
                      var userInfo = res.data.data.user
                      if (userInfo && !userInfo.avatarUrl) {
                        userInfo.avatarUrl = version.defaultAvataUrl
                      }
                      wx.setStorageSync('userInfo', userInfo);
                      app.globalData.userInfo = userInfo
                      app.globalData.hasUserInfo = true
                      app.globalData.auth = true
                      wx.setStorageSync('auth', true);
                      that.setData({
                        auth: true,
                        userInfo: app.globalData.userInfo,
                        hasPhone: app.globalData.hasPhone,
                      });
                      // 业务
                      wx.navigateTo({
                        url: '/pages/upload/upload?dataObj=' + itemEncode,
                        success: function() {},
                        fail: function() {},
                        complete: function() {}
                      })
                      // 业务
                    }
                    if (res && res.data.code == 301) {
                      wx.setStorageSync('token', res.data.data.token);
                      app.globalData.token = res.data.data.token;
                      app.globalData.hasPhone = false
                      wx.setStorageSync('hasPhone', false);
                      that.setData({
                        hasPhone: false,
                      });
                      that.auth.showAuth();
                    }

                  }
                })
              }
            })
          })
          //防止緩存失效带来的问题
        } else {
          that.auth.showAuth()
        }
      })
    } //else

  },

  login: function() {
    return new Promise(function(resolve, reject) {
      wx.login({
        success: function(res) {
          if (res.code) {
            //登录远程服务器
            resolve(res);
          } else {
            reject(res);
          }
        },
        fail: function(err) {
          reject(err);
        }
      });
    });
  },

  onShareAppMessage: function(ops) {
    if (ops.from === 'button') { //页面内转发按钮     

    } else {
      return {
        title: '邀请您来同感Live分享现场',
        desc: '邀请您来同感Live分享现场',
        path: '/pages/index/index',
        imageUrl: 'http://simul.dpaper.cn/miniprogram/show_images/share_logo.jpeg',
        success: function(res) {},
        fail: function(res) {}
      }
    }
  },

})